package by.koleda.photoupdater;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import by.koleda.photoupdater.helpers.ImageLoader;
import by.koleda.photoupdater.manager.ContactsManager;

public class ContactsActivity extends Activity {
	
	private SimpleCursorAdapter dataAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.activity_contacts);
		
		displayListView();
	}

	private void displayListView() {
		Cursor cursor = ContactsManager.getContacts(this);
		
		String[] columns = new String[] {
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.Contacts._ID
		};
		
		int[] to = new int[] {
				R.id.contacts_contact_name,
				R.id.contacts_contact_image
		};
		
		dataAdapter = new SimpleCursorAdapter(this, R.layout.adapter_contacts, cursor, columns, to, 0);
		
		ListView listView = (ListView) findViewById(R.id.listview_contacts);
		
		ViewBinder viewBinder = new ViewBinder() {

			@Override
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if (view.getId() == R.id.contacts_contact_image) {
					ImageView imageView = (ImageView) view;
					ImageLoader.get(ContactsActivity.this).loadContactBitmap(imageView, cursor.getString(columnIndex));
					return true;
				}
				return false;
			}
		};
		
		dataAdapter.setViewBinder(viewBinder);
		listView.setAdapter(dataAdapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> listView, View view, int position,
					long id) {
				Cursor cursor = (Cursor) listView.getItemAtPosition(position);
				Intent intent = new Intent(ContactsActivity.this, ProfileActivity.class);
				intent.putExtra(ProfileActivity.EXTRA_PROFILE_MESSAGE, cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)));
				startActivityForResult(intent, 0);
			}
		});
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == RESULT_OK) {
			dataAdapter.notifyDataSetChanged();
		}
	}
}
